package cn.com.xy.sms.sdk.ui.popu.simplepart;

import android.app.Activity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.List;

import cn.com.xy.sms.sdk.constant.Constant;
import cn.com.xy.sms.sdk.ui.R;
import cn.com.xy.sms.sdk.ui.popu.util.BottomButtonUtil;
import cn.com.xy.sms.sdk.ui.popu.util.ContentUtil;
import cn.com.xy.sms.sdk.ui.popu.util.SmartSmsSdkUtil;
import cn.com.xy.sms.sdk.ui.popu.widget.SimpleBottomTable;

public class SimpleBubbleBottom extends RelativeLayout {

    public static final String TAG = "SimpleBubbleBottom";
    public Activity mContext;
    private SimpleBottomTable mSimpleBottomTable;

    public SimpleBubbleBottom(Activity mContext, JSONArray jsonArray, HashMap<String, Object> extend) throws Exception {
        super(mContext);
        this.mContext = mContext;
        int layoutId = R.layout.duoqu_simple_bubble_lay;
        inflate(Constant.getContext(), layoutId, this);

        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
        this.setLayoutParams(params);

        initViews(mContext, extend);
        setContent(jsonArray, extend);
    }

    private void initViews(Activity context, HashMap<String, Object> extend) {
        mSimpleBottomTable = (SimpleBottomTable) findViewById(R.id.duoqu_simple_bubble_lay_simplebottomtable);
        mSimpleBottomTable.setDisLogo(true);
    }

    public void setContent(JSONArray jsonArray, HashMap<String, Object> extend) {
        try {
            jsonArray = getAdAction(jsonArray);
            if (jsonArray == null || jsonArray.length() <= 0) {
                setVisibility(View.GONE);
                return;
            }
            setVisibility(View.VISIBLE);
            List<JSONArray> arrays = ContentUtil.getSimpleBubbleData(jsonArray, 3);
            int dataSize = arrays.size();
            mSimpleBottomTable.setContentList(arrays, dataSize);
        } catch (Throwable e) {
            SmartSmsSdkUtil.smartSdkExceptionLog(TAG, e);
        }
    }

    private JSONArray getAdAction(JSONArray jsonArray) throws JSONException {
        if (jsonArray == null || jsonArray.length() <= 0)
            return null;
        JSONArray tempJsonArr = new JSONArray();
        for (int i = 0; i < jsonArray.length(); i++) {
            JSONObject tempObject = BottomButtonUtil.getButtonItem(jsonArray.optJSONObject(i), "", null);
            if (tempObject != null) {
                tempJsonArr.put(tempObject);
            }
        }

        return tempJsonArr;
    }
}
